package com.shop.controller;

import com.shop.entity.LoginUser;
import com.shop.entity.ReturnMessage;


import com.shop.service.LoginUserService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;




@Controller
public class LoginUserController {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;
    @Autowired
    LoginUserService loginUserService;

    /**
     * 登录
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/admin/login")
    public ReturnMessage login(LoginUser user) {
        logger.info("登录开始：{}", user);
        if (user == null || user.getPwd() == null || user.getUserName() == null) {
            return new ReturnMessage(0, "参数不能为空！", null);
        }
        String name = "";
        LoginUser loginUser = loginUserService.get(user);

        //密码匹配
        boolean matches = bCryptPasswordEncoder.matches(user.getPwd(), loginUser.getPwd());
        if (matches) {
            return new ReturnMessage(0, "用户名或密码错误！", null);
        } else {
            return new ReturnMessage(0, "登录成功！", loginUser);
        }
    }

    /**
     * 增加
     * @param user
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add")
    public ReturnMessage add(LoginUser user) {
        logger.info("add开始：{}", user);
        int add = 0;
        try {
            String pwd = user.getPwd();
            String encryptPwd = bCryptPasswordEncoder.encode(pwd);
            user.setPwd(encryptPwd);
            add = loginUserService.add(user);
            if (add >= 0) {
                return new ReturnMessage(0, "添加成功！", null);
            } else {
                return new ReturnMessage(0, "添加失败！", null);
            }
        } catch (Exception e) {
            return new ReturnMessage(0, "添加异常！", null);
        }

    }


}
